package br.pucrs.lognplay.faces.bean;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import br.pucrs.lognplay.entity.Client;
import br.pucrs.lognplay.entity.DynamicView;
import br.pucrs.lognplay.entity.User.Role;
import br.pucrs.lognplay.service.DynamicViewManagementService;

@ManagedBean
@ViewScoped
public class DynamicViewManagementBean extends Bean {

	private DynamicView dynamicView;

	@EJB
	private DynamicViewManagementService dynamicViewManagementService;

	public DynamicView getDynamicView() {
		try {
			if (dynamicView == null) {
				String dynamicViewId = getParameterValue("dynamicViewId");

				if (dynamicViewId == null) {
					Client loggedUserClient = getLoggedUser().getClient();
					dynamicView = loggedUserClient.getDynamicView();
				} else {
					dynamicView = dynamicViewManagementService.getDynamicViewById(dynamicViewId);
				}
			}

			return dynamicView;
		} catch (Exception e) {
			throw new BeanException("Unexpected error", e);
		}
	}

	public void setDynamicView(DynamicView dynamicView) {
		this.dynamicView = dynamicView;
	}

	public boolean isClientRendered() {
		Role loggedUserRole = getLoggedUser().getRole();

		if (loggedUserRole.equals(Role.MASTER_USER)) {
			return true;
		} else {
			return false;
		}
	}

	public String save() {
		try {
			dynamicViewManagementService.mergeDynamicView(dynamicView);
			addInformationMessage("The changes have been saved", null);
			return null;
		} catch (Exception e) {
			throw new BeanException("Unexpected error", e);
		}
	}
}
